<template>
  <div class="page-container page-footer-btn">
    <van-cell-group>
      <van-field v-model="form.matrName" label="耗材" is-link clearable placeholder="请选择耗材" @focus="open" />
      <FortenScan
        ref="scan"
        propPlaceholder="请扫描GTIN码"
        propErrorMsg="请扫描GTIN码"
        :propTypeArr="['GTIN']"
        @scanCall="handleScanOver"
      />
    <van-divider><span style="font-size:15px">商品信息</span></van-divider>
    <van-field label="耗材名称" :value="form.name" readonly />
    <van-field label="HIS名称" :value="form.hisName" readonly />
    <van-field label="耗材品规" :value="form.spec" readonly />
    <van-field label="厂商" :value="form.mfgName" readonly />
    <van-field label="寄售模式" :value="form.flagConsignment+ ''" readonly />
    <van-field label="GTIN码" :value="form.gtin" readonly />
    <van-field label="注册证号" :value="form.certificateNo" readonly />
    <van-field label="注册证效期" :value="form.certificateExp" readonly />
    <van-field label="单品单位" :value="form.skuUnit" readonly />
    <van-field label="单品价格" :value="form.skuPrice" readonly />
    </van-cell-group>
    <van-collapse v-model="pictureActiveNames">
      <van-collapse-item title="商品图片" name="1">
        <van-uploader v-model="fileList" multiple
          capture="camera"
          :max-size="1000 * 1024"
          :max-count="5"
          :after-read="afterRead"
          :before-delete="fileDelete"
          @oversize="onOversize"/>
      </van-collapse-item>
    </van-collapse>
   <!-- <van-collapse v-model="locationActiveNames">
      <van-collapse-item title="默认库位" name="1">
        <van-field class="scan"
          ref="scanLocation"
          v-model="scanLocation"
          left-icon="scan"
          placeholder="请扫描库位编码进行绑定"
          size="large"
          clearable
          border
          @keyup.enter.native="handleScanLocationOver"
        />
        <van-row>
          <van-col span="8">仓库</van-col>
          <van-col span="8">库位</van-col>
          <van-col span="8">操作</van-col>
        </van-row>
        <van-row v-for="(matrLocation,index) in matrLocations" :key="index" class="location">
          <van-col span="8">{{matrLocation.warehouseName}}</van-col>
          <van-col span="8">{{matrLocation.locationName}}</van-col>
          <van-col span="8"><van-button size="small" type="danger" @click="delMartLocation(matrLocation.id, index)">删除</van-button></van-col>
        </van-row>
      </van-collapse-item>
    </van-collapse>-->
    <van-collapse v-model="packageActiveNames">
      <van-collapse-item title="包装列表" name="1">
        <van-row>
          <van-col span="8">单位</van-col>
          <van-col span="8">换算比</van-col>
          <van-col span="8">价格</van-col>
        </van-row>
        <van-row v-for="(unit, index) in units" :key="index">
          <van-col span="8">{{unit.unit}}</van-col>
          <van-col span="8">{{unit.rate}}</van-col>
          <van-col span="8">{{unit.price}}</van-col>
        </van-row>
      </van-collapse-item>
    </van-collapse>

    <FortenList ref="listItem" :propAutoFetchData = 'false'
                :propIsRadio="true"
                :propFlagPopup="true"
                :propSearchFields="['name','spec']"
                :propSearchTextAppend="'品名/品规'"
                propUrl="/base/matr/page"
                @change="change"
    >
      <template  #default="{item}"  >
        <van-row >
          <van-col span="4">
            <van-radio   :name="item"  />
          </van-col>
          <van-col span="4">品名：</van-col>
          <van-col span="14">{{item.name}}</van-col>
        </van-row>
        <van-row  >
          <van-col span="4">
          </van-col>
          <van-col span="4">品规：</van-col>
          <van-col span="14">{{item.spec}}</van-col>
        </van-row>
      </template>

    </FortenList>
  </div>
</template>
<script>
import barcodeParse from '@/util/barcodeParse.js'

export default {
  name: 'matrSet',
  data() {
    return {
      scan: '',
      scanLocation: '',
      form: {},
      currentLocation: {},
      showmatrAction: false,
      matrList: [],
      matrFilterResult: [],
      matrLocations: [],
      locationActiveNames: ['1'], //默认库位
      pictureActiveNames: ['1'], //图片
      packageActiveNames: ['1'], //包装单位
      fileList: [],
      units: [],
      fileRefTable: 'base_matr',
      baseApi: location.origin + '/api'
    }
  },
  props: {
    propFlowKey: String
  },
  components: {
  },
  methods: {
    //扫描
    handleScanOver(scanValue) {
      let codeType = barcodeParse.barCodeType(scanValue)
      if (codeType != 'GTIN') {
        this.$notify.warning('请扫描有效的GTIN')
        return
      }
      let  gtinAnalysis = barcodeParse.gtinAnalysis(scanValue)
      let gtin = ''
      if (gtinAnalysis.gtin) {
        gtin = gtinAnalysis.gtin
      } else {
        this.$notify.warning('不支持该GTIN编码的规则,请添加规则')
        window.scanError()
        return
      }
      let wrapper = this.$newWrapper().eq('gtin', gtin)
      let params = {
        isScan: 1,
        queryString: JSON.stringify(wrapper.queryConditions)
      }
      this.$ajax.get('/base/matr/list', {params}).then(resp => {
        if (resp.data && resp.data.length > 0) {
          this.form = resp.data[0]
          this.afterMatrSelect()
        } else {
          this.$notify.warning('不能识别的GTIN！')
          return
        }
        this.scan = ''
      })
    },
    delMartLocation(matrLocationId, index) { //删除默认库位
      let params = {
        ids: [matrLocationId]
      }
      this.$ajax.delete('/location/limit_matr/delete', {data: params}).then(resp => {
        this.matrLocations.splice(index, 1)
      })
    },
    handleScanLocationOver() { //添加新的默认库位
      if (window.isPDAScan()) this.scanLocation = window.getPDAScan()

      if (!this.form.id) {
        this.$notify.warning('请先选择耗材')
        return
      }
      if (!this.scanLocation) {
        this.$notify.warning('请扫描库位编码')
        return
      }
      let wrapper = this.$newWrapper().eq('idcode', this.scanLocation)
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions)
      }
      this.$ajax.get('/base/location/list', {params}).then(resp => {
        if (resp.data && resp.data.length > 0) {
          this.currentLocation = resp.data[0]
          this.bindMatrLocation()
        } else {
          this.$notify.warning('不能识别的库位编码！')
          return
        }
        this.scanLocation = ''
      })
    },
    bindMatrLocation() { //绑定新的库位
      if (!this.currentLocation || !this.currentLocation.id) {
        return
      }
      if (this.matrLocations.find(location => location.warehouseId == this.currentLocation.warehouseId) != null) {
        this.$notify.warning('该仓库已经绑定过默认库位，不能重复绑定')
        return
      }
      let params = {
        matrId: this.form.id,
        matrName: this.form.name,
        matrSpec: this.form.spec,
        locationIdcode: this.currentLocation.idcode,
        warehouseId: this.currentLocation.warehouseId,
        locationId: this.currentLocation.id,
        locationName: this.currentLocation.name
      }
      this.$ajax.post('/location/limit_matr/save', params).then(resp => {
        this.getmatrLocations()
      })
    },
    onOversize() {
      this.$notify.warning('文件大小不能超过1MB')
    },
    getfiles() { //获取商品图片
      let params = {
        fileRefTable: this.fileRefTable,
        fileRefId: this.form.id
      }
      this.$ajax.get('/tool/getFilesByRef', {params}).then((response) => {
        if (response.data && response.data.length) {
          this.fileList = response.data.map(file => {
            return {
              url: this.baseApi + file.filePath,
              id: file.id
            }
          })
        }
      })
    },
    async fileDelete(file) { //删除附件
      let params = {
        fileId: file.id
      }
      await this.$ajax.get('/tool/delFilesByRef', {params}).then(resp => {
        if (resp.success) {
          return true
        }
        return false
      })
    },
    afterRead(file) { //上传图片
      let params = new FormData()
      params.append('file', file.file)
      params.append('fileSavePath', this.fileRefTable)
      params.append('fileRefTable', this.fileRefTable)
      params.append('fileRefId', this.form.id)
      this.$ajax.post('/tool/uploadMore', params, {headers: {'Content-Type': 'multipart/form-data'}}).then(resp => {
        if (resp.code == 0) {
          // this.fileList.splice(this.fileList.length - 1, 1)
          this.getfiles()
        }
      })
    },
    matrfilter() {
      this.matrFilterResult = this.matrList.filter(item => item.name.indexOf(this.form.matrName) > -1 || item.spec.indexOf(this.form.matrName) > -1).slice(0, 500)
    },
    getmatrLocations() { //获取所有的默认库位
      if (!this.form.id) {
        this.matrLocations = []
        return
      }
      let wrapper = this.$newWrapper().eq('matrId', this.form.id)
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions)
      }
      this.$ajax.get('/location/limit_matr/list', {params}).then(resp => {
        this.matrLocations = resp.data
      })
    },
    getMatrs() {
      // this.$ajax.get('/base/matr/list').then(resp => {
      //   this.matrList = resp.data
      //   this.matrFilterResult = this.matrList.slice(0, 500)
      // })
    },
    getUnits() {
      let params = {
        matrId: this.form.id
      }
      this.$ajax.get('/base/matrUnit/getByMatr', {params}).then(resp => {
        this.units = resp.data
      })
    },
    //耗材选择事件
    matrtoggle(item, index) {
      this.showmatrAction = false
      if (this.form.id == item.id) {
        return
      }
      this.form = item
      this.afterMatrSelect()
    },
    afterMatrSelect() {
      this.matrLocations = []
      this.fileList = []
      this.units = []
      this.getmatrLocations()
      this.getfiles()
      this.getUnits()
    },
    open() {
      this.$refs.listItem.show()
    },
    change(item) {
      this.form = item
      this.form.matrId = item.id
      this.form.matrName = item.name
      this.afterMatrSelect()
    },
    reload() {
      this.$refs.scan.focus()
      this.form = {}
      this.matrLocations = []
      this.fileList = []
      this.units = []
    }
  },
  mounted() {
    this.$refs.scan.focus()
  }
}
</script>

<style lang="scss" scoped>
  .van-col {
    text-align: center;
  }
  .location {
    line-height: 40px;
    text-align: center;
    font-size: 15px;
  }
</style>
